package com.we.wfc.common.pojo;

import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.ObjectUtil;
import com.we.wfc.common.base.BaseException;
import com.we.wfc.common.base.BaseJpaEntity;
import com.we.wfc.common.enums.ReturnCode;
import com.we.wfc.common.utils.CommonUtil;
import com.we.wfc.common.utils.ExcelUtil;
import lombok.Data;
import lombok.experimental.Accessors;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.function.BiFunction;

/**
 * Excel 导出工厂，简化ExcelUtil，调用
 *
 * @author zhangby
 * @date 26/1/20 1:53 pm
 */
@Data
@Accessors(chain = true)
public class ExcelFactory {
    /**
     * 响应对象
     */
    private HttpServletResponse response;
    /**
     * 导出对象名
     */
    private String fileName;
    /**
     * 是否需要添加标题
     */
    private String title;
    /**
     * 同时设置title and fileName
     */
    private String titleAndFileName;
    /**
     * 导出别名
     * eg: id:ID,wxName:用户名,balanceStatus:状态
     */
    private String alias;
    /**
     * 列宽
     * eg: id:100,wxName:200,balanceStatus:200
     */
    private String columnWidth;
    /**
     * 默认列宽
     */
    private Integer defaultColumnWidth;

    /**
     * 私有化构造器
     */
    private ExcelFactory() {
    }

    /**
     * 构建返回对象
     */
    public static ExcelFactory builder() {
        return new ExcelFactory();
    }

    /**
     * 导出excel
     */
    public void export4Map(List<Dict> list, BiFunction<Dict, String, String> function) {
        // 参数验证
        if (ObjectUtil.isNull(response)) {
            throw new BaseException(ReturnCode.DOWNLOAD_FAILURE_NOT_SET_RESPONSE);
        }
        ExcelUtil.export4Map(
                response,
                CommonUtil.emptyStr(fileName).orElse(titleAndFileName),
                CommonUtil.emptyStr(title).orElse(titleAndFileName),
                alias,
                columnWidth,
                defaultColumnWidth,
                list,
                function
        );
    }

    /**
     * 导出excel
     */
    public void export4Map(List<Dict> list) {
        export4Map(list, null);
    }

    /**
     * 导出excel
     */
    public <T extends BaseJpaEntity> void export(List<T> list, BiFunction<T, String, String> function) {
        // 参数验证
        if (ObjectUtil.isNull(response)) {
            throw new BaseException(ReturnCode.DOWNLOAD_FAILURE_NOT_SET_RESPONSE);
        }
        ExcelUtil.export(
                response,
                CommonUtil.emptyStr(fileName).orElse(titleAndFileName),
                CommonUtil.emptyStr(title).orElse(titleAndFileName),
                alias,
                columnWidth,
                defaultColumnWidth,
                list,
                function
        );
    }

    /**
     * 导出excel
     */
    public <T extends BaseJpaEntity> void export(List<T> list) {
        export(list, null);
    }
}
